<?php

namespace app\util;

/*
 * 红包
 */
class Redpacket
{
    const MIN_MONEY = 0.01;
    const MAX_MONEY = 200;
    const TIMES = 2.1;

    /*
     * 返回红包
     */
    public function splitRedPackets($money, $count)
    {
        if (!$this->isRight($money, $count)) {
            return null;
        }
        $list = [];
        $max = (float)($money * self::TIMES / $count);
        $max = $max > self::MAX_MONEY ? self::MAX_MONEY : $max;
        for ($i = 0; $i < $count; $i++) {
            $one = $this->randomRedPacket($money, self::MIN_MONEY, $max, $count - $i);
            array_push($list, $one);
            $money -= $one;
        }
        return $list;
    }

    /*
     * 判断红包金额是否正确
     */
    public function isRight($money, $count)
    {
        $avg = $money / $count;
        if ($avg < self::MIN_MONEY) {
            return false;
        } else if ($avg > self::MAX_MONEY) {
            return false;
        }
        return true;
    }

    /*
     * 生成红包金额
     */
    public function randomRedPacket($money, $mins, $maxs, $count)
    {
        if ($count == 1) {
            return (float)(round($money * 100)) / 100;
        }
        if ($mins == $maxs) {
            return $mins;//如果最大值和最小值一样，就返回mins
        }
        $max = $maxs > $money ? $money : $maxs;
        $rand = $this->randFloat(0, 1);
        $one = (float)$rand * ($max - $mins) + $mins;
        $one = (float)(round($one * 100)) / 100;
        $moneyOther = $money - $one;
        if ($this->isRight($moneyOther, $count - 1)) {
            return $one;
        } else {
            //重新分配
            $avg = $moneyOther / ($count - 1);
            if ($avg < self::MIN_MONEY) {
                return $this->randomRedPacket($money, $mins, $one, $count);
            } else if ($avg > self::MAX_MONEY) {
                return $this->randomRedPacket($money, $one, $maxs, $count);
            }
        }
        return $one;
    }

    /*
     * 生成0-1之间随机数
     */
    public function randFloat($min = 0, $max = 1)
    {
        return $min + mt_rand() / mt_getrandmax() * ($max - $min);
    }


}